#!/usr/bin/env python
#usage: fill_tab.py table.ini result.txt
import numpy as np
from astropy.table import Table
import sys

ini = sys.argv[1]
fout = sys.argv[2]

f = open(ini)
lines = f.readlines()
output = np.zeros((len(lines),2))
# processed/ptc_0104/ptc_result.tab full 0 16 min 0 0.001
f = open(fout,'w')
for i in range(len(lines)):
    print(lines[i].split(' '))
    line_list = lines[i].split(' ')
    tab = Table.read(line_list[0],format='ipac')
    key = line_list[1]
    l = int(line_list[2])
    h = int(line_list[3])
    row = []
    if len(line_list) >= 6:
        worst_flag = line_list[4]
    elif len(line_list) == 5:
        worst_flag = line_list[4][:-1]
    #print(line_list[5])
    data = tab[key][l:h]*float(line_list[6][:-1])
    if worst_flag == 'absmax':
        data = abs(data)
    mean = np.mean(data)
    if worst_flag == 'max' or worst_flag == 'absmax':
        worst = np.max(data)
    elif worst_flag == 'min':
        worst = np.min(data)
    elif worst_flag == 'dark':
        mean = np.max(data)
        worst = -1
    
    if line_list[5][-1] == 'e':
        #print('{:.'+line_list[5][:-1]+'e}')
        mean = '{:.2e}'.format(float(mean))
        worst = '{:.2e}'.format(float(worst))
    else:
        mean = str(np.round(mean,int(line_list[5])))
        worst = str(np.round(worst,int(line_list[5])))
    row.append(mean+" ")
    row.append(worst+"\n")
    f.writelines(row)
f.close()
